package api

import (
	"encoding/json"
	"pan/common/conf"
	"pan/common/encrypt"
	"pan/common/exception"
	"pan/common/log"
	"pan/common/net"
	"pan/common/util"
)

type LoginRequest struct {
	Account  string `json:"account"`
	Password string `json:"password"`
}

type LoginResponse struct {
	FailRsponse

	Expires            int64  `json:"expires"`
	NeedModifyPassword bool   `json:"needmodifypassword"`
	Tokenid            string `json:"tokenid"`
	Userid             string `json:"userid"`
}

func LoginApi(req *LoginRequest) (*LoginResponse, error) {
	url := util.PathJoin(conf.GlobalConfig.Url, conf.GlobalConfig.Paths.Login)

	enPassword, err := encrypt.RsaEncrypt(req.Password, conf.GlobalRsaPubKey.GetKey())
	if err != nil {
		return nil, err
	}

	request := &LoginRequest{
		Account:  req.Account,
		Password: enPassword,
	}

	if log.IsDebugEnable() {
		bytes, _ := json.Marshal(request)
		log.Debug("login post: ", url, ", body:", string(bytes))
	}

	resp := &LoginResponse{}
	if err = net.Post(url, request, resp); err != nil {
		return nil, err
	}
	if log.IsDebugEnable() {
		result, _ := json.Marshal(resp)
		log.Debug("login response: ", string(result))
	}

	if resp.Errcode != 0 {
		return nil, exception.NewExpectError("login failed, %s", resp.FailString())
	}
	conf.GlobalToken.SetExpires(resp.Expires)
	conf.GlobalToken.Tokenid = resp.Tokenid
	conf.GlobalToken.Userid = resp.Userid
	if err = conf.GlobalToken.Save(); err != nil {
		return nil, err
	}
	return resp, nil
}
